export function colorTo(val, to = '#', opacity = 1) {
	if (val.includes(to)) {
		return val
	} else if (val.includes('#')) {
		return hexToRgba(val,opacity)
	} else if (val.includes('rgb')) {
		return rgbaToHex(val)
	}
}


/**
 * 16进制颜色值转rgba
 * @param {string} hex 16进制颜色
 */
export function hexToRgba(hex, opacity = 1) {
	let RGBA = "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt(
		"0x" + hex.slice(5, 7)) + "," + opacity + ")";
	return RGBA
}
/**
 * rgba转16进制
 * @param {string} color rgba 
 */
export function rgbaToHex(color) {
	if (!color) return console.warn('rgba转16进制时传入的颜色值不能为空')
	if (color.includes('rgba')) {
		let values = color
			.replace(/rgba?\(/, '')
			.replace(/\)/, '')
			.replace(/[\s+]/g, '')
			.split(',');
		let a = parseFloat(values[3] || 1),
			r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
			g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
			b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
		return "#" +
			("0" + r.toString(16)).slice(-2) +
			("0" + g.toString(16)).slice(-2) +
			("0" + b.toString(16)).slice(-2);
	} else {
		return color
	}

}
/**
 * 动态计算颜色值
 * @param {*} hex 十六进制颜色值，例如“#abc”或“＃123456”（散列是可选的）
 * @param {*} lum  亮度因数，即，-0.1是10％更暗，0.2是轻20％等
 */
export function colorLuminance(hex, lum = 0) {
	hex = hex.trim()
	hex = hex?hex:'#ccc'
	hex = String(hex).replace(/[^0-9a-f]/gi, "");
	if (hex.length < 6) {
		hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
	}
	let rgb = "#";
	for (let i = 0; i < 3; i++) {
		let c = parseInt(hex.substr(i * 2, 2), 16);
		c = Math.round(Math.min(Math.max(0, c + c * lum), 230)).toString(16);
		rgb += ("00" + c).substr(c.length);
	}
	return rgb;
}